<?php
namespace app\back\controller;

use \app\back\model\Account as AccountModel;
use \app\back\model\AccountMoney as AccountMoneyModel;

class Account extends \app\common\controller\BaseController
{   
    private $register_success_text = '会员开通成功，正在跳往充值页面...';
    private $register_exists_text = '会员已存在，正在跳往详情页面...';
    private $recharge_success_text = '充值成功，正在跳往详情页面...';
    private $recharge_failed_text = '充值失败，再来一次吧...';

    protected $beforeActionList = [
        'accountValidate' =>  ['only'=>'detail'],
    ];

    /*
     * 会员列表
     */
    public function accountList() {
        $data['view_type'] = input('get.view_type');

        $account_model = model('Account');
        $data['view_type_arr'] = $account_model->stateConfigArr();

        if(array_key_exists($data['view_type'], $data['view_type_arr'])) 
            $account_model->where('state', '=', $data['view_type']);

        $data['list'] = $account_model->order('create_time DESC')->select();

        return $this->fetch('list', $data);
    }

    /*
     * 注册会员
     */
    public function register() {

        if(request()->isPost()) {
            // 检测是否存在
            if(!($account_model = AccountModel::get(['mobile'=>input('post.mobile')]))) {
                // 创建会员
                $account_model = new AccountModel();
                // 验证数据合法性
                $result = $account_model->allowField(['mobile'])->validate('account')->save($_POST);

                if(false === $result){
                    // 验证失败 输出错误信息
                    $data['register_error_message'] = $account_model->getError();
                } else {
                    // 创建成功，页面跳转至充值页面
                    $this->success($this->register_success_text, url('back/account/recharge', ['mobile'=>$account_model->mobile]), '', 2);
                }
            } else {
                // 会员存在，跳转至详情页
                $this->success($this->register_exists_text, url('back/account/detail', ['mobile'=>$account_model->mobile]), '', 2);
            }
        }
        // 模板变量
        $data['mobile'] = request()->isPost()?input('post.mobile'):input('get.search_mobile');
        $data['action_url'] = url('/back/account/register');
        return $this->fetch('/account/register', $data);
    }

    /*
     * 会员消费
     */
    public function consumption() {
        if(request()->isPost()) {
            $account_money_model = new AccountMoneyModel($_POST);
            $result = $account_money_model->consumption();

            if($result === false) {
                $message = $account_money_model->error_message;
                $this->error($message, url('back/account/consumption',['mobile'=>$account_money_model->mobile]), '', 2);
            } else {
                $message = '消费成功，即将跳转到记录页';
                $this->success($message, url('back/account/detail', ['mobile'=>$account_money_model->mobile]), '', 2);
            }
        }

        $data['action_url'] = url('/back/account/consumption');
        $data['mobile'] = input('request.mobile');


        return $this->fetch('', $data);
    }

    /*
     * 会员充值
     */
    public function recharge() {

        $money_model =  model('AccountMoney');
        // 判断是否有数据提交
        if(request()->isPost()) {
            // 限制更新字段，赋值模型数据
            switch (input('post.charge_type')) {
                case 'times':
                    // 进行充值操作
                    $result = $money_model->timesRecharge();
                    break;
                
                default:
                    // 进行充值操作
                    $result = $money_model->recharge();
                    break;
            }

            if(false === $result){
                // 验证失败 输出错误信息
                $data['recharge_error_message'] = $money_model->error_message;
                $this->error($money_model->error_message, url('back/account/recharge', ['mobile'=>$money_model->mobile, 'type'=>input('post.charge_type')]), '', 2);
            } else {
                $this->success($this->recharge_success_text, url('back/account/detail', ['mobile'=>$money_model->mobile]), '', 2);
            }
        }
        // 模板变量
        $data['action_url'] = url('back/account/recharge');
        $data['mobile'] = input('request.mobile');
        $data['detail_url'] = url('back/account/detail', ['mobile'=>$data['mobile']]);
        $data['today'] = date('Y-m-d');
        $data['one_month'] = date('Y-m-d', strtotime('+1 month'));
        $data['one_year'] = date('Y-m-d', strtotime('+1 year'));
        $data['account_recharge_money'] = input('?request.mobile') ? AccountMoneyModel::where('mobile', input('request.mobile'))->value('recharge_money') : 0;

        return $this->fetch('', $data);
    }

    /*
     * 查询到的会员详情
     */
    public function detail() {
        // 接收会员信息
        $mobile = input('request.mobile');
        // 查询会员信息
        $userinfo = AccountModel::get(['mobile'=>$mobile,]);

        // 会员不存在，进行注册引导
        if(empty($userinfo)) 
            goto jump;

        // 会员信息
        $data['userinfo'] = $userinfo;
        // 充值地址
        $data['recharge_url'] = url('back/account/recharge',['mobile'=>$userinfo->mobile]);
        // 消费地址
        $data['consumption_url'] = url('back/account/consumption',['mobile'=>$userinfo->mobile]);
        // 记录地址
        $data['record_url'] = url('back/account/record',['mobile'=>$userinfo->mobile]);
        $data['edit_url'] = url('back/account/edit',['mobile'=>$userinfo->mobile]);

        return $this->fetch('', $data);

        jump:
        $this->redirect('back/account/register', ['search_mobile'=>$mobile], 200);
    }

    /*
     * 修改会员信息
     */
    public function edit($mobile) {
        $userinfo = AccountModel::get(['mobile'=>$mobile,]);

        if(request()->isPost()) {
            $money_model =  AccountMoneyModel::get(['mobile'=>$mobile]);

            $result = $money_model->AMoneyEdit();
            if(false === $result){
                // 验证失败 输出错误信息
                $data['recharge_error_message'] = $money_model->error_message;
                $this->error($money_model->error_message, url('back/account/edit', ['mobile'=>$mobile]), '', 2);
            } else {
                $this->success('修改成功', url('back/account/detail', ['mobile'=>$mobile]), '', 2);
            }
        }

        $data = [
            'userinfo' => $userinfo,
            'mobile' => $mobile,
        ];

        return $this->fetch(null, $data);
    }

    /*
     * 用户消费记录
     */
    public function record($mobile) {
        $data['view_type'] = input('get.view_type');

        $account_record_model = model('AccountRecord');
        $data['view_type_arr'] = $account_record_model->rechargeTypeConfig();

        $account_record_model->where('mobile','=',$mobile);

        if(array_key_exists($data['view_type'], $data['view_type_arr'])) {
            $account_record_model->where('recharge_type','=',$data['view_type']);
        }

        if(input('get.statistics') == 'statistics') {
            $data['list'] = $account_record_model->customerStatistics($mobile);
        } else {
            $data['list'] = $account_record_model->order('create_time DESC')->select();
        }

        $data['mobile'] = $mobile;
        $data['record_url'] = url('back/account/record', ['mobile'=>$mobile]);
        $data['statistics_url'] = url('back/account/record', ['mobile'=>$mobile, 'statistics'=>'statistics']);
        $data['detail_url'] = url('back/account/detail', ['mobile'=>$mobile]);

        return $this->fetch('', $data);
    }

    /*
     * 会员手机号验证
     */
    protected function accountValidate($message='') {

        if(!input('?request.mobile')) {
            $message = '请输入会员帐号';
            goto jump;
        }

        if(($message = $this->validate(['mobile'=>input('request.mobile'), '__token__'=>request()->token()], 'account')) !== true) {
            goto jump;
        }

        return true;
        jump:
        $this->redirect('back/index/index', [], 301, ['search_message'=>$message]);
    }
}
